/*****目标团队--靶标 --攻防赛*****/
<template><!---->
	<search-table
	    ref="searchTable"
		:columns="targetTeamCol" 
		:data="targetAllotList"
		:total=	targetAllotTotal
		:page="queryTargetAllotInfo.pageIndex"
		:size.sync="queryTargetAllotInfo.pageSize"
		showSelectTag
		selectName="targetName"
		:selection.sync="selectTargetAllots"
		@change-size="getTargetSize"
		@change-page="getTargetPage"
	>
	<Alert type="warning" show-icon v-if="step == 'pre' && configMode !== 1" slot="alert">
		<p style="color:#f90">注意事项（下发的规则在“路由规则下发记录”中都可以查看到，如果状态为失败，可以重新下发，如果下发内容有误，可以修改下发内容重新下发）:</p>
		<p>	1.第一步进行“一键配置”</p>
		<p>	2.第二步进行“下发规则”</p>
		<p v-if="![8, 9].includes(type)">	3.第三步进行“题目对应虚拟机密码修改”之前，必须在环境的题目中创建相应的用户且同一个团队的所有题目对应虚拟机的用户名必须一致</p>
	</Alert>
	<template slot="search">
		<!--<Button  type='primary' ghost @click="showAddAndUpdate('')" :disabled="disabledAllBtn"><img src="../../../../assets/scene/target-allot-purple.png" alt="" />靶标分配</Button>-->
		<!-- <Checkbox v-model="selectAll" @on-change="handleCheckAll" v-if="type === 8" style="margin-right:15px;">全选</Checkbox> -->
		<Button  type='primary' ghost @click="autoAllotTopoTarget()" v-if="configMode !== 1"
			:disabled="disabledAllBtn || targetTeamTotal == 0" class="mr15"><img src="../../../../assets/scene/auto-target-allot-purple.png" alt="" />一键配置</Button>
		<!-- <Button  type='primary' ghost icon="md-add" @click="autoAllotTopoTargetTip()" :disabled="disabledAllBtn || targetTeamTotal == 0" class="mr15">下发基础配置</Button>
		<Button  type='primary' ghost icon="md-add" @click="portForward()" :disabled="disabledAllBtn || targetTeamTotal == 0" class="mr15">下发端口转发规则</Button> -->
		<Button type='primary' ghost icon="ios-nuclear-outline" @click="issuedRules" :loading="issuedLoading" 
			 v-if="configMode !== 1" :disabled="disabledAllBtn" class="mr15">下发规则</Button>
		<Poptip 
			v-if="type === 8"
		  :disabled="disBatchShowBtn || targetTeamTotal < 1"
		  confirm
		  ok-text="攻击机"
		  cancel-text="防守机"
		  title="请选择要批量重置的机器"
		  transfer
		  @on-ok="batchResetDockerVm(1)"
		  @on-cancel="batchResetDockerVm(0)">
		  <Button 
			  type="primary" 
			  ghost 
			  style="margin-right:15px;">批量重置</Button>
		</Poptip>
		<Button  type='primary' v-if="![8, 9].includes(type)" ghost @click="showModifyPwd" :disabled="disabledAllBtn || targetTeamTotal == 0" class="mr15">
			<img src="../../../../assets/scene/modify-password-purple.png" alt=""/>
			题目对应虚拟机密码修改
		</Button>
		<Select filterable v-model="queryTargetAllotInfo.visibility" placeholder="是否显示" @on-change="getTargetPage(1)" clearable style="width:150px;margin-right:15px;">
			 <Option  :value="1">是</Option>
			 <Option  :value="0">否</Option>
		</Select>
		  <Select filterable v-model="queryTargetAllotInfo.teamName"
				  style="width: 150px; margin-right:15px;"
				  @on-change="getTargetPage(1)" clearable
				  placeholder="请选择团队">
			  <Option v-for="item in teamList" :value="item.name" :key="item.id" :title="item.name">{{ item.name }}</Option>
		  </Select>
		  <Select filterable v-model="queryTargetAllotInfo.targetName"
				  style="width: 150px; margin-right:15px;"
				  @on-change="getTargetPage(1)" clearable
				  placeholder="请选择题目">
			  <Option v-for="item in targetTeamData" :value="item.name" :key="item.id" :title="item.name">{{ item.name }}</Option>
		  </Select>
	</template>
    <Modal v-model="targetModal.show"
      	:title="targetModal.title"
      	:loading = "targetModal.loading"
      	width="800px"
      	:mask-closable = "false"
      	@on-cancel="closeTargetModal"
      	@on-ok="targetAllot">
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
          <FormItem label="靶标" prop="targetId">
            <Select filterable v-model="formValidate.targetId" placeholder="请选择靶标" @on-change="changeTarget" filterable>
              <Option  v-for="target in targetTeamData" :value="target.id" :key="target.id" :title="target.name">{{target.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="人员设备" prop="idsTOS" v-show="formValidate.targetId">
            <!--{{formValidate.idsTOS}}-->
            <!--<Row>
            	<Table size="small" :columns="idsTOSCol" :data="formValidate.idsTOS"></Table>
            </Row>-->
            <!--<Table size="small" :columns="idsTOSCol" :data="formValidate.idsTOS"></Table>-->
          </FormItem>
          <Table size="small" :columns="idsTOSCol" :data="formValidate.idsTOS" v-show="formValidate.targetId"></Table>
         </Form>
         <Form ref="addFormValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
          <Card v-show="formValidate.targetId">
          <FormItem label="团队" prop="teamId">
            <Select filterable  v-model="formValidate.teamId" placeholder="请选择团队" @on-change="changeTeamGroup">
              <Option  v-for="item in accessGroupList" :value="item.id"  :key="item.id" :title="item.name">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="子网络" prop="subnetId">
            <Select filterable  v-model="formValidate.subnetId" placeholder="请选择子网络" @on-change="changeSubnet">
              <!--<Option value="all">所有</Option>-->
              <Option  v-for="item in subnetList" :value="item.id"  :key="item.id" :title="item.name">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="虚拟机" prop="vmId">
            <Select filterable v-model="formValidate.vmId" placeholder="请选择虚拟机" filterable @on-change="changeVm">
              <Option v-for="item in vmlists" :value="item.id" :key="item.id" :title="item.name">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem  label="是否显示" prop="visibility">
            <RadioGroup v-model="formValidate.visibility">
              <Radio :label=1>显示</Radio>
              <Radio :label=0>不显示</Radio>
            </RadioGroup>
            <span style="color:#f90" v-if="type == 4"> <Icon type="ios-information-circle-outline"/>用于在演练页面的展示控制</span>
            <span style="color:#f90" v-if="[1, 8, 9].includes(type)"> <Icon type="ios-information-circle-outline"/>用于在竞赛页面的展示控制</span>
          </FormItem>
          <FormItem  label="外网IP" prop="externalIp">
            <Input v-model.trim="formValidate.externalIp" placeholder="请输入对外IP" readonly disabled></Input>
          </FormItem>
          <Button type="info" ghost long @click="addIdTOS">添加人员设备</Button>
          </Card>
        </Form>
      </Modal>
      <Modal v-model="modifyTargetModal.show"
      	:title="modifyTargetModal.title"
      	:loading = "modifyTargetModal.loading"
      	width="600px"
      	:mask-closable = "false"
      	@on-cancel="handleReset('allotFormValidate')"
      	@on-ok="modifyTargetAllot">
        <Form ref="allotFormValidate" :model="allotFormValidate" :rules="ruleValidate" :label-width="100">
          <FormItem label="靶标" prop="basicTargetId">
            <Select filterable v-model="allotFormValidate.basicTargetId" placeholder="请选择题目" @on-change="changeTarget" filterable>
              <Option  v-for="target in targetTeamData" :value="target.id" :key="target.id" :title="target.name">{{target.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="团队" prop="teamId">
            <Select filterable  v-model="allotFormValidate.teamId" placeholder="请选择团队">
              <Option  v-for="item in accessGroupList" :value="item.id"  :key="item.id" :title="item.name">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="子网络" prop="subnetId">
            <Select filterable  v-model="allotFormValidate.subnetId" placeholder="请选择子网络" @on-change="changeSubnet">
              <!--<Option value="all">所有</Option>-->
              <Option  v-for="item in subnetList" :value="item.id"  :key="item.id" :title="item.name">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="虚拟机" prop="vmId">
            <Select filterable v-model="allotFormValidate.vmId" placeholder="请选择虚拟机" filterable>
              <Option v-for="item in vmlists" :value="item.id" :key="item.id" :title="item.name">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem  label="是否显示" prop="visibility">
            <RadioGroup v-model="allotFormValidate.visibility">
              <Radio :label=1>显示</Radio>
              <Radio :label=0>不显示</Radio>
            </RadioGroup>
            <span style="color:#f90" v-if="type == 4"> <Icon type="ios-information-circle-outline"/>用于在演练页面的展示控制</span>
            <span style="color:#f90" v-if="[1, 8, 9].includes(type)"> <Icon type="ios-information-circle-outline"/>用于在竞赛页面的展示控制</span>
          </FormItem>
          <FormItem  label="外网IP" prop="externalIp">
            <Input v-model.trim="allotFormValidate.externalIp" placeholder="请输入对外IP"></Input>
          </FormItem>
          <!--<FormItem  label="外网服务端口 " prop="externalServicePort" v-if="type == 1">
            <Input v-model.trim="allotFormValidate.externalServicePort" placeholder="请输入PORT(1~65535)"></Input>
          </FormItem>
          <FormItem  label="外网访问端口" prop="externalPort">
            <Input v-model.trim="allotFormValidate.externalPort" placeholder="请输入PORT(1~65535)"></Input>
          </FormItem>-->
        </Form>
      </Modal>
      <Modal v-model="loading"
      	title="路由下发"
      	width="400px"
      	:mask-closable = "false"
      	:closable="false"
      	footer-hide
      	>
        <h3><Icon type="ios-loading" size=24 class="demo-spin-icon-load" style="margin-right:24px;"></Icon>{{distriTip}} <span v-if="minDown > 0">{{minDown}}</span></h3>
    	<Alert type="warning" show-icon style="margin-top:10px;">请勿离开此页面！！</Alert>
	  </Modal>
    <modify-pwd ref="modifyPwd"></modify-pwd>
  </search-table>
</template>

<script>
  import {getTargetTeamList_new,queryVmWithParty,queryNetworkList,targetAllot,VRIPRelation,queryTargetAllot,queryTargetAllotRelation,modifyTargetAllot,autoAllotTopoTarget,getExecutionsResult, resetDockerVm} from '@/api/drill_compete'
  import {queryCtfList} from '@/api/question'
  import {getFlagServerList,getstatusbyprjid,hxRouterVms,issuedRules} from '@/api/drill'
  import {getaccessgrouplist} from '@/api/access_new'
  import modifyPwd from './modifyPwd'
  import disRouteFun from "@/view/drill_compete/page/targetTeam/mixin"
  import groupMixin from '@/mixin/groupMixin'
	export default {
    name: 'scenes',
    props:['type','disabledAllBtn','step', 'configMode','disbledSelect'],
    components:{modifyPwd},
    mixins:[disRouteFun, groupMixin],
	data(){
		const validateNum = (rule, value, callback) => { //验证只能填入数字
	      	var reg = new RegExp("^([1-9]|[1-9]\\d|100)$");
	      	//验证警戒值
	      	if(value){
	      		if (!reg.test(value)) {
	      			callback(new Error('请输入1-100的整数'));
	      		}else{
	      			callback()
	      		}
	      	}else{
	      		callback()
	      	}
	      }
		const validatePort = (rule, value, callback) => { //验证只能填入数字
	      	var reg = new RegExp("^([1-9][0-9]{0,1}|65535)$");
	      	//验证警戒值
	      	if(value){
	      		if (!reg.test(parseInt(value))) {
	      			callback(new Error('请输入1-65535的整数'));
	      		}else{
	      			callback()
	      		}
	      	}else{
	      		callback()
	      	}
	      }
	      const validateIP = (rule, value, callback) => { //验证只能填入数字
	      	var reg = new RegExp("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
	      	//验证警戒值
	      	if(value){
	      		if (!reg.test(value)) {
	      			callback(new Error('ip格式错误'));
	      		}else{
	      			callback()
	      		}
	      	}else{
	      		callback()
            }
            }
        return {
			selectAll: false,
            issuedLoading: false,
            routeParams:{
                id:this.$route.query.id,
                prjid:this.$route.query.prjid
            },
            targetModal:{
                show:false,
                title:'',
                loading:true,
                type:1 //1添加，2修改
            },
	        modifyTargetModal:{
	        	show:false,
	        	title:'修改分配',
	        	loading:true
	        },
	        pathList:[],
			accessGroupList:[],
	        vmlists:[],
	        allVms:[],
	        teamlists:[],
			queryTargetTeamInfo:{
				pageIndex:1,
				pageSize:2147483647,
				sceneId:this.$route.query.id,
				projectId:this.$route.query.prjid
			},
			queryTargetAllotInfo:{
				pageIndex:1,
				pageSize:10,
				sceneId:this.$route.query.id,
				spare: 0, // 需要过滤掉备用环境
			},
	        questionList:[],
	        access:'1',
	        formValidate: {
			  "idsTOS": [],
			  "subnetId": "",
			  "subnetName": "",
			  "targetId": "",
			  "vmId":"",
			  "vmName":"",
			  "teamId": "",
      		  "teamName": "",
			  "externalIp": "", //对外ip
//			  "externalPort": "", //对外端口
//			  "externalServicePort":"",
			  "visibility": 0,
	        },
	        allotFormValidate:{
			  "createTime": "",
			  "externalIp": "",
//			  "externalPort": "",
//			  "externalServicePort": "",
			  "id": "",
			  "sceneId": "",
			  "subnetId": "",
			  "subnetName": "",
			  "targetId": "",
			  "targetName": "",
			  "teamId": "",
			  "teamName": "",
			  "visibility": 0,
			  "vmId": "",
			  "vmName": "",
			  "basicTargetId":""
	        },
	        oldFormValidate:{},
	        ruleValidate: {
			  subnetId:[
	          	{ required: true, message: '请选择子网络', trigger: 'change'}
	          ],
	          questionId:[
	          	{ required: true, message: '请选择题目', trigger: 'change'}
	          ],
	          visibility:[
	          	{ required: true, type:'number',message: '请选择', trigger: 'change'}
	          ],
	          vmId:[
	          	{ required: true, message: '请选择虚拟机', trigger: 'change'}
	          ],
	          teamId:[
	          	{ required: true, message: '请选择团队', trigger: 'change'}
	          ],
	          targetId:[
	          	{ required: true, message: '请选择靶标', trigger: 'change'}
	          ],
	          basicTargetId:[
	          	{ required: true, message: '请选择靶标', trigger: 'change'}
	          ],
	          idsTOS:[
	          	{ required: true,type:'array',min:1, message: '请添加人员设备', trigger: 'change'}
	          ],
//	          externalPort:[
//	          	{ validator: validatePort, trigger: 'change' }
//	          ],
//	          externalServicePort:[
//	          	{ validator: validatePort, trigger: 'change' }
//	          ],
	          externaIp:[
	          	{ validator: validateIP, trigger: 'change' }
	          ]
	        },
	        querytime:{},
	        targetTeamCol:[
	//        {
	//          type: 'index',
	//          align: 'center',
	//          ellipsis:true,
	////          width:60
	//        },
			{
				type: 'selection',
				align:'center',
				width:60,
				show:(data) => {
					return this.type === 8 //!([8, 9].includes(this.type) && this.disbledSelect)
				}
				// placement:'top-left',
				// render:(h,params) => {
				// 	return h('Checkbox',{
				// 		props:{
				// 			value:params.row._checked
				// 		},
				// 		on:{
				// 			'on-change':(e) => {
				// 				this.selectSingle(e,params.row);
				// 			}
				// 		}
				// 	})
				// }
			},
	          {
	            title:'题目显示名称',
	            key:'targetName',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            placement:'top-left',
                  width: 200
	          },
		      {
	        	title:'子网络名称',
	            key:'subnetName',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            placement:'top-left',
                  width: 100
		      },
		      {
	            title:'团队名称',
	            key:'teamName',
	            align:'center',
	            placement:'top-left',
                  tooltip:true,
                  width: 100
//	            render:(h, params) => {
//	              return h('span',this.typeFilter(params.row.type))
//	            }
	          },
	          {
	            title:'虚拟机名称',
	            key:'vmName',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            placement:'top-left',
                  width: 100
	//          width:100
	          },
//	          {
//	            title:'团队名称',
//	            key:'teamName',
//	            align:'center',
//	            ellipsis:true,
//	            tooltip:true,
//	            width:100
//	          },

	//        {
	//          title:'验证码类型',
	//          key:'targetsubmittype',
	//          align:'center',
	//          width:140,
	//          render:(h, params) => {
	//            return h('span',this.targetSubmitTypeFilter(params.row.targetsubmittype))
	//          }
	//        },
	//        {
	//          title:'虚拟机名称',
	//          key:'vmname',
	//          align:'center',
	//          ellipsis:true,
	//          tooltip:true,
	//        },
			  {
	            title:'内网IP',
	            key:'ip',
	            align:'center',
	            ellipsis:true,
                tooltip:true,
	            width: 112
	          },
	          {
	            title:'内网访问端口',
	            key:'port',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
                width:40
	          },
	          {
	            title:'内网服务端口',
	            key:'servicePort',
	            align:'center',
	            ellipsis:true,
				tooltip:true,
				width:40
	          },
	          {
	            title:'路径',
	            key:'flagPath',
	            align:'center',
				tooltip:true,
				width:120
//	            render:(h,params) => {
//	            	console.log(params.row.targetTempInfos.filter(t => t.type == 1))
//	            	return h('span',params.row.targetTempInfos.filter(t => t.type == 1).length > 0 ? params.row.targetTempInfos.filter(t => t.type == 1)[0].info : '')
//	            }
	          },
	          {
	            title:'外网IP',
	            key:'externalIp',
	            align:'center',
	            ellipsis:true,
				tooltip:true,
				width: 112,
				show:() => {
					return ![8, 9].includes(this.type)
				}
	          },
	          {
	            title:'外网访问端口',
	            key:'externalPort',
	            align:'center',
	            ellipsis:true,
				tooltip:true,
				width: 40,
				show:() => {
					return ![8, 9].includes(this.type)
				}
	          },
	          {
	            title:'外网服务端口',
	            key:'externalServicePort',
	            align:'center',
	            ellipsis:true,
				tooltip:true,
				width: 40,
				show:() => {
					return ![8, 9].includes(this.type)
				}
	          },
	          {
	            title:'用户名',
	            key:'user',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
				width: 80,
				show:() => {
					return ![8, 9].includes(this.type)
				}
	          },
	          {
	            title:'密码',
	            key:'password',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
				width: 80,
				show:() => {
					return ![8, 9].includes(this.type)
				}
	          },
                {
                    title:'分值',
                    key:'score',
                    align:'center',
                    ellipsis:true,
                    tooltip:true,
                    placement:'top-right',
                    width: 50
                },
	          {
	            title:'显示状态',
	            key:'visibility',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            placement:'top-right',
	            render:(h,params) => {
					return h('Tag',{
						props:{
						   color:params.row.visibility == 1 ? 'var(--status-yes)' : 'var(--status-no)',
						   type:"border",
						   title:'点击切换'
						},
						style:{
							cursor: this.configMode === 1 || [8, 9].includes(this.type) ? '' : 'pointer !important'
						},
						nativeOn:{
		                    click:()=>{
								if (this.configMode === 1 || [8, 9].includes(this.type)) { // 攻防赛plus、简单模式不允许切换分配靶标的展示状态
									return
								}
		                    	let visibility = 0;
		                    	if(params.row.visibility == 0){
		                    		visibility = 1;
		                    	}
		                    	modifyTargetAllot(params.row.id,{visibility:visibility}).then(data => {
						   	   	  if(data.code == 1){
						   	   	  	this.queryTargetAllot();
						   	   	  	this.$Message.info('操作成功');
						   	   	  }else{
						   			this.$Message.warning(data.message);
						   		  }
						   	    }).catch(error => {
						   			this.$Message.error(error);
						   		})
		                      //this.showAddAndUpdate(params.row)
		                    }
		                }
					},params.row.visibility == 1 ? '是' : '否' )
				}
	          },
	          {
	            title:'描述',
	            key:'description',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
                  width: 300
	          },
			  {
				title: '操作',
				width: 100,
				key:'action',
				placement:'top-right',
				show:this.type === 8,
				// opList:[
				// 	{
				// 		txt:'重置',
				// 		title: '请选择要重置的机器',
				// 		disabled: this.disabledAllBtn,
				// 		tooltip:true
				// 	}
				// ],
				render: (h, params) => {
					return h('div', [
						h('Poptip', {
							props: {
								confirm: true,
								'ok-text':"攻击机",
								'cancel-text':"防守机",
								type: 'error',
								size: 'large',
								title: '请选择要重置的机器',
								transfer:true,
							},
							on: {
								'on-ok': () => {
									this.resetDockerVm(params.row.id, 1)
								},
								'on-cancel': () => {
									this.resetDockerVm(params.row.id, 0)
								}
							}
						}, [
							h('Button', {
								props: {
									type: 'primary',
									size: 'small',
									disabled: this.disabledAllBtn,
									// icon: 'md-refresh'
								},
								attrs: {
									title: '重置'
								},
								style: {
									background: 'none',
									border: 'none',
									boxShadow: 'none',
									// 'font-size': '24px',
									padding: '0 2px 6px 2px',
									color: this.disabledAllBtn ? 'var(--operation-unuseable)' : 'var(--operation-useable)'
								},
								on: {
									click: () => {
									}
								}
							},'重置')
						])
					])
				}
			}
//	          {
//	            title:'操作',
//	            key:'os',
//	            ellipsis:true,
//	            width:100,
//	            render:(h,params)=>{
//	              return h('div',[
//	                h('Button',{
//	                  props:{
//	                    type:'primary',
//	                    size:'small'
//	                  },
//	                  style:{
//	                    marginRight:'5px'
//	                  },
//	                  on:{
//	                    click:()=>{
	                      //this.showAddAndUpdate(params.row)
//	                      this.modifyTargetModal.show = true;
//	                      this.allotFormValidate = JSON.parse(JSON.stringify(params.row));
//	                      this.changeSubnet(this.allotFormValidate.subnetId);
//	                      this.getAllVmlist().then(data => {
//	                      	this.allotFormValidate = JSON.parse(JSON.stringify(params.row));
//	                      	this.changeSubnet(this.allotFormValidate.subnetId);
//	                      });
//	                    }
//	                  }
//	                },'修改'),
//	                h('Poptip', {
//	                  props: {
//	                    confirm: true,
//	                    'ok-text': "确定",
//	                    'cancel-text': "取消",
//	                    type: 'error',
//	                    size: 'large',
//	                    title: '你确定要删除吗?'
//	                  },
//	                  on: {
//	                    'on-ok': () => {
//	                      this.delTargetTeam(params.row.id)
//	                    }
//	                  }
//	                }, [
//	                  h('Button', {
//	                    props: {
//	                      type: 'error',
//	                      size: 'small'
//	                    },
//	                    style: {
//	                      marginRight: '5px'
//	                    },
//	                  }, '删除')
//	                ])
//	              ])
//	            }
//	          }
	        ],
	        idsTOSCol:[
	          {
	            title:'团队',
	            key:'teamName',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	          },
	          {
	            title:'子网络',
	            key:'subnetName',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	          },
	          {
	            title:'虚拟机',
	            key:'vmName',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	          },
	          {
	            title:'外网IP',
	            key:'externalIp',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	          },
//	          {
//	            title:'外网访问端口',
//	            key:'externalPort',
//	            align:'center',
//	            ellipsis:true,
//	            tooltip:true,
//	          },
//	          {
//	            title:'外网服务端口',
//	            key:'externalServicePort',
//	            align:'center',
//	            ellipsis:true,
//	            tooltip:true,
//	          },
	          {
	            title:'是否显示',
	            key:'visibility',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            render:(h,params) => {
					return h('Tag',{
						props:{
						   color:params.row.visibility == 1 ? 'success' :'default',
						   type:"border"
						},
						on:{
		                    click:()=>{
		                      //this.showAddAndUpdate(params.row)
		                    }
		                }
					},params.row.visibility == 1 ? '是' : '否' )
				}
	          },
	          {
	            title:'操作',
	            key:'action',
	            ellipsis:true,
//	            width:200,
	            render:(h,params)=>{
	              return h('div',[
	                h('Button',{
	                  props:{
	                    type:'primary',
	                    size:'small'
	                  },
	                  style:{
	                    marginRight:'5px'
	                  },
	                  on:{
	                    click:()=>{
	                        let index = this.formValidate.idsTOS.findIndex(item => item.id == params.row.id);
	                        this.formValidate.idsTOS.splice(index,1);
	                    }
	                  }
	                },'移除')
	              ])
	            }
	          }
	        ],
	        targetTeamData:[],
	        targetTeamTotal:0,
	        TargetId:'',
	        projectInfo:{},
	        subnetList:[],
	        networkId:'',
	        teamArr:[],
	        networkArr:[],
	        vmArr:[],
	        idwithName:{},
	        targetAllotList:[],
			selectTargetAllots:[],
	        targetAllotTotal:0,
	        loading:false,
			distriTip:'',
			minDown:0
	  	}
	},
	filters:{

	},
	computed:{
		showQuestionList(){ //选出部署了题目镜像虚拟机的题目
			let quesList = [];
			this.questionList.forEach(ques => {
				if(this.allVms.map(vm => vm.imageName).includes(ques.imageName)){
					quesList.push(ques)
				}
			})
			return quesList;
		},
		disBatchShowBtn(){
			return this.selectTargetAllots.length === 0
		},
	},
	mounted(){
    	this.getProjectInfo();
    	this.getAccessGroupList();
    	//this.getAllVmlist(true);
    	this.getTargetTeamList();
    	this.queryTargetAllot();
    	if(this.type == 1){
//  		this.idsTOSCol.splice(2, 0, {
//	            title:'服务内网端口',
//	            key:'externalServicePort',
//	            align:'center',
//	            ellipsis:true,
//	            tooltip:true,
//	        });
//	        this.targetTeamCol.splice(7, 0, {
//	            title:'服务内网端口',
//	            key:'externalServicePort',
//	            align:'center',
//	            ellipsis:true,
//	            tooltip:true,
//	        });
    	}
		if ([8, 9].includes(this.type)) {
			// let index = this.targetTeamCol.findIndex(item => item.title === '外网IP')
			// if (index !== -1) {
			// 	this.targetTeamCol.splice(index, 1)
			// }
			// index = this.targetTeamCol.findIndex(item => item.title === '外网服务端口')
			// if (index !== -1) {
			// 	this.targetTeamCol.splice(index, 1)
			// }
			// index = this.targetTeamCol.findIndex(item => item.title === '外网访问端口')
			// if (index !== -1) {
			// 	this.targetTeamCol.splice(index, 1)
			// }
			// index = this.targetTeamCol.findIndex(item => item.title === '用户名')
			// if (index !== -1) {
			// 	this.targetTeamCol.splice(index, 1)
			// }
			// index = this.targetTeamCol.findIndex(item => item.title === '密码')
			// if (index !== -1) {
			// 	this.targetTeamCol.splice(index, 1)
			// }
			// index = this.targetTeamCol.findIndex(item => item.key === 'select')
			// if (index !== -1 && this.disbledSelect) { // 运维赛不需要复选框
			// 	this.targetTeamCol.splice(index, 1)
			// }
		}
		// if (this.type === 8) { // 攻防赛plus需要提供重置功能
		// 	let index = this.targetTeamCol.findIndex(item => item.title === '操作')
		// 	if (index !== -1) {
		// 		this.targetTeamCol.splice(index, 1, this.activeOption)
		// 	} else {
		// 		this.targetTeamCol.push(this.activeOption)
		// 	}
		// }
	},
    methods:{
		batchResetDockerVm(type) {
			if (this.disBatchShowBtn) {
				return
			}
			let list = this.selectTargetAllots;
			Promise.all(list.map(item => resetDockerVm({
				targetId: item.id,
				sceneId: this.$route.query.id,
				type // 0：重置防御机  1：重置攻击机
			}))).then(res => {
				if (res.every(item => item.code === 1)) {
					this.$Message.success('批量重置成功')
					this.handleCheckAll(false)
				} else {
					this.$Message.warning('批量重置失败')
				}
			})
		},
		handleCheckAll(e){
			this.selectAll = e;
			this.targetAllotList.forEach(target => {
				this.selectSingle(e,target);
			})
		},
		selectSingle(e,target){
			this.$set(target,'_checked',e);
			if(this.targetAllotList.every(target => target._checked === true)){
				this.selectAll = true;
			}else{
				this.selectAll = false;
			}
		},
		resetDockerVm(targetId, type) {
			resetDockerVm({
				targetId,
				sceneId: this.$route.query.id,
				type // 0：重置防御机  1：重置攻击机
			}).then(({ code, message }) => {
				if (code !== 1) {
					this.$Message.warning(message)
					return
				}
				this.$Message.success('重置成功')
				this.getTargetPage()
			}).catch(() => {
                this.$Message.error(`重置机器异常`);
            })
		},
		// 下发团队规则或者竞赛系统路由规则
        issuedRules() {
            this.issuedLoading = true
            issuedRules(this.$route.query.id).then(async ({ code, message, data }) => {
                if (code !== 1) {
					this.cancelBtnLoading()
                    this.$Message.warning(message)
                } else {
                    this.$Message.info('下发规则成功')
					// self->TabPane->Tabs->hwDrillDetail，所以需要三个$parent
					this.$parent.$parent.$parent.preDefault = 'routerRules'
                }
            }).catch(() => {
                this.cancelBtnLoading()
                this.$Message.error(`下发规则异常`);
            })
        },
		cancelBtnLoading() {
            this.issuedLoading = false
        },
    	getProjectInfo(){
			getstatusbyprjid(this.$route.query.prjid).then(data => {
				if(data.code == 1){
					this.projectInfo = data.attribute;
					this.getProjectSubnet();
				}
			})
		},
		getTargetTeamList(){
	  		getTargetTeamList_new(this.queryTargetTeamInfo).then(data => {
	  			if(data.code==1){
	  				this.targetTeamData = data.data.items || data.data;
	  				this.targetTeamData.forEach(team => {
						this.idwithName[team.id] = {
							name:team.name,
							id:team.id,
							imageName:team.imageName,
							imageId:team.imageId,
							ip:team.ip
						};
					})
	  				this.targetTeamTotal = data.data.total;
	  			}else{

	  			}
	  		})
	  	},
    	initData(){
    		this.formValidate = {
			  "idsTOS": [],
			  "subnetId": "",
			  "subnetName": "",
			  "targetId": "",
			  "externalIp": "", //对外ip
			  "externalPort": "", //对外端口
			  "externalServicePort":"",
			  "visibility": 0,
			}
    	},
    	getAllVmlist(){
    		return new Promise((resolve,reject) => {
	        let params = {
				page:1,
				pageSize:10000,
				sortBy:'name',
				order:'asc',
				findPorts:true,
			}
	        if(this.formValidate.targetId){
	        	params.imageId = this.idwithName[this.formValidate.targetId].imageId;
	        	console.log(params.imageId);
	        }
	        if(this.allotFormValidate.basicTargetId){
	        	params.imageId = this.idwithName[this.allotFormValidate.basicTargetId].imageId;
	        }
	        if(this.group){
	        	//params.party = this.group.partyId;
	        }
	        if(this.targetModal.show && this.formValidate.subnetId){
	        	params.networkId = this.formValidate.subnetId;
	        }
	        if(this.modifyTargetModal.show && this.allotFormValidate.subnetId){
	        	console.log(this.allotFormValidate.subnetId)
	        	params.networkId = this.allotFormValidate.subnetId;
	        }
	        if(this.modifyTargetAllot.show && this.allotFormValidate.subnetId){
	        	params.networkId = this.allotFormValidate.subnetId;
	        }
			queryVmWithParty(this.routeParams.prjid,params).then(data => {
//		    getProjectSevers(params).then(data => {
				if(data.code == 1){
					this.vmlists = data.data.list || data.data;
					console.log(this.vmlists);
					this.formValidate.vmId = '';
					this.formValidate.vmName='';
					if(this.targetModal.show && this.vmlists.length > 0){
			    		this.formValidate.vmId = this.vmlists[0].id;
			    		this.formValidate.vmName = this.vmlists[0].name;
//			    		this.queryTargetAllotRelation();
		//	    		this.formValidate.idsTOS = [];
			    	}else if(this.modifyTargetModal.show && this.vmlists.length > 0){
//			    		setTimeout(() => {
//			    			this.allotFormValidate.vmId = this.vmlists[0].id;
//			    			this.allotFormValidate.vmName = this.vmlists[0].name;
//			    		})
			    	}
					this.vmlists.forEach(vm => {
						this.idwithName[vm.id] = {
							id:vm.id,
							name:vm.name
						}
					})
					resolve();
					//this.getVmIp(this.formValidate.vmId);
//					if(this.vmlists.length > 0){
//						let server = this.vmlists.filter(vm => vm.id == this.formValidate.vmId)[0];
//	    		        if(server){
//	    		        	this.formValidate.subnet = server.addresses[0].subnetId;
//	    		        	this.getFlagServerList(server.address[0].ipv4);
//	    		        	this.getFlagServerList(server.addresses[0].ip);
//	    		        }
//					}
				}
			})
			})
	    },
        getAccessGroupList(){
			if(!this.routeParams.id){
				return;
			}
			let params = {
				pageIndex:1,
				pageSize:2147483647,
				testId:this.routeParams.id
			};
			this.selectGroupList = [];
			getaccessgrouplist(params).then(data => {
				if(data.code == 1){
					this.accessGroupList = data.data.items;
					this.accessGroupList.forEach(group => {
						this.idwithName[group.id] = {
							id:group.id,
							name:group.name
						}
					})
				}else if(data.code == -2) {
					this.accessGroupList = [];
				}else{
					this.$Message.warning(data.message);
				}
			})
		},
		showAddAndUpdate(info){
    		this.initData();
    		this.targetModal.show = true;
    		if(!info){
    			this.targetModal.title = '题目分配';
    			this.targetModal.type = 1;
    			this.access = "1";
    		}else{

    		}
    		console.log(this.formValidate)
    	},
    	handleReset (name) {
	        this.$refs[name].resetFields();
	        this.addTarget = false;
	        this.initData();
	        console.log(this.formValidate);
	        this.$refs [name].fields.forEach(function (e) {
			     if (e.fieldValue != undefined && e.fieldValue!='') {
			          e.resetField()
			      }
			})
	    },
	    addTargetTeam(){
	  		let params = JSON.parse(JSON.stringify(this.formValidate));
	  		params.questionName = this.question.name;

	  	},
	  	modifyTargetTeam(){
	  		let params = JSON.parse(JSON.stringify(this.formValidate));
	  		params.questionName = this.question.name;
	  	},
	  	saveTargetTeam(){
	  		this.$refs['formValidate'].validate((valid) => {
	            if (valid) {
	            	if(this.targetModal.type == 1){
	            		this.addTargetTeam();
	            	}else{
	            		this.modifyTargetTeam();
	            	}
	            }else{
	            	this.cancelLoading('targetModal');
	            }
	        })
	    },
	    getTargetSize(size){
	        this.queryTargetAllotInfo.pageSize = size;
	        this.queryTargetAllot();
	    },
	    getTargetPage(page){
	        this.queryTargetAllotInfo.pageIndex = page || this.queryTargetAllotInfo.pageIndex;
	        this.queryTargetAllot();
	    },
	    changeTeamGroup(){

	    },
	    changeTarget(targetId){
	    	if(this.targetModal.show){
	    		this.formValidate.vmId = '';
	    		this.formValidate.vmName = '';
	    		this.formValidate.subnetId = '';
	    		this.formValidate.subneName = '';
	    		this.formValidate.teamId = '';
	    		this.formValidate.teamName = '';
	    		this.formValidate.externalIp = '';
	    		this.formValidate.externalPort = '';
	    		this.formValidate.externalServicePort = '';
	    		this.queryTargetAllotRelation();
	    	}else if(this.modifyTargetModal.show){
	    		this.allotFormValidate.vmId = '';
	    		this.allotFormValidate.vmName = '';
	    	}
	    	this.getAllVmlist();
	    },
	    changeSubnet(id){
	    	if(!id){
	    		return;
	    	}
//	    	if(this.targetModal.show){
//	    		this.formValidate.vmId = '';
//	    		this.formValidate.vmName = '';
//	    		this.queryTargetAllotRelation();
////	    		this.formValidate.idsTOS = [];
//	    	}else if(this.modifyTargetModal.show){
//	    		this.allotFormValidate.vmId = '';
//	    		this.allotFormValidate.vmName = '';
//	    	}
			if(this.targetModal.show){
				this.formValidate.externalIp = this.idwithName[this.formValidate.subnetId].ip;
			}else if(this.modifyTargetModal.show){
				this.allotFormValidate.externalIp = this.idwithName[id].ip;
			}
	    	this.getAllVmlist();
	    },
	    changeVm(){

	    },
	    getProjectSubnet(){
	    	queryNetworkList(this.$route.query.prjid,this.projectInfo.network.id).then(data => {
	    		if(data.code == 1){
	    			let subnetList = [];
	    			let linkList = [];
	    			data.attribute.editorStage.childs.forEach(item => {
	    				subnetList = subnetList.concat(item.childs);
	    				if(item.links){
	    					linkList = linkList.concat(item.links);
	    				}
	    			})
	    			this.subnetList = subnetList.filter(subnet => subnet.dataType == 'NW');
	    			this.subnetList.forEach(subnet => {
	    				let ip;
	    				if([1, 8, 9].includes(this.type)){
	    					if(linkList.filter(link => link.rightNetId == subnet.id).length > 0){
	    						ip = linkList.filter(link => link.rightNetId == subnet.id)[0].rightIpParts[0].ipAddress;
	    						this.$set(subnet,'ip',ip);
	    					}
	    				}
						this.idwithName[subnet.id] = {
							id:subnet.id,
							name:subnet.name,
							ip:ip
						}
					})
	    		}
	    	})
	    },
	    initAllotForm(){
	    	this.formValidate.vmId = '';
    		this.formValidate.vmName = '';
    		this.formValidate.subnetId = '';
    		this.formValidate.subneName = '';
    		this.formValidate.teamId = '';
    		this.formValidate.teamName = '';
    		this.formValidate.externalIp = '';
    		this.formValidate.externalPort = '';
    		this.formValidate.externalServicePort = '';
	    },
	    addIdTOS(){
	    	this.$refs['addFormValidate'].validate((valid) => {
	            if (valid) {
//	            	if(this.targetModal.type == 1){
//	            		this.addTargetTeam();
//	            	}else{
//	            		this.modifyTargetTeam();
//	            	}
					this.formValidate.idsTOS.push({
			    		"vmId":this.idwithName[this.formValidate.vmId].id,
						"vmName":this.idwithName[this.formValidate.vmId].name,
						"teamId":this.idwithName[this.formValidate.teamId].id,
			      		"teamName":this.idwithName[this.formValidate.teamId].name,
			      		"subnetId":this.formValidate.subnetId,
					    "subnetName":this.idwithName[this.formValidate.subnetId].name,
						"externalIp":this.formValidate.externalIp, //对外ip
						"externalPort": this.formValidate.externalPort, //对外端口
						"externalServicePort":this.formValidate.externalServicePort,
						"visibility": this.formValidate.visibility
			    	})
					this.initAllotForm();
//	            }else{
////	            	this.cancelLoading('targetModal');
	            }
	        })
	   },
	   targetAllot(){
	    	this.$refs['formValidate'].validate((valid) => {
	            if (valid) {
			   	    let params = {
					  "idsTOS": this.formValidate.idsTOS,
//					  "subnetId":this.formValidate.subnetId,
//					  "subnetName":this.idwithName[this.formValidate.subnetId].name,
					  "targetId": this.formValidate.targetId
					}
			   	    targetAllot(params).then(data => {
			   	    	if(data.code == 1){
			   	    		this.queryTargetAllot();
			   	    		if([1, 8, 9].includes(this.type)){
			   	    			this.VRIPRelation();
			   	    		}
			   	    		this.targetModal.show = false;
			   	    		this.formValidate.vmId = '';
			   	    		this.formValidate.teamId = '';
			   	    		this.formValidate.visibility = 0;
			   	    	}else{
			   	    		this.cancelLoading('targetModal');
			   	    	}
			   	    }).catch(error => {
			   	    	this.cancelLoading('targetModal');
			   	    })
			    }else{
			    	this.cancelLoading('targetModal');
			    }
	   		})
	   },
	   awaitWrap(promise){
		  return promise
		   .then(data => [null, data])
		   .catch(err => [err, null])
	   },
	   async autoAllotTopoTargetTip(){
	   	  if(this.hxRouterVmList.length == 0){
	    		this.$Message.info('没有核心路由，请查看工程是否部署，核心路由未下发！！！');
	    		return;
	      }
//	   	  for(let i = 0;i< this.subnetList.length;i++){
//	   	  	let code = "#!/bin/vbash\nsource /opt/vyatta/etc/functions/script-template\n configure \n#指定变量 \nwancidr=192.168.50. \nwaneth=`ip a | grep  $wancidr | awk '{print $7}'`\nfirename=local\n";
//	   	  	let subnet = this.subnetList[i];
//	   	  	for(let j = 0;j<this.targetTeamData.length;j++){
//	   	  		console.log(this.subnetList[i],this.targetTeamData[j]);
//	   	  		let target = this.targetTeamData[j];
//	   	  		let ipLast = Number(target.ip.split('.').pop());
//	   	  		code += `
// 	  		    target${j+1}_ip=${target.ip}
//				target${j+1}_port=${target.servicePort}
//				target${j+1}wan_ip=${subnet.ip}
//				target${j+1}wan_port=${target.externalServicePort}
//				#配置端口转发
//				set nat destination rule ${ipLast-10} description 'Port Forward: $target${j+1}_ip:$target${j+1}_port to $target${j+1}wan_ip:$target${j+1}wan_port'
//				set nat destination rule ${ipLast-10} inbound-interface $waneth
//				set nat destination rule ${ipLast-10} destination address $target${j+1}wan_ip
//				set nat destination rule ${ipLast-10} destination port $target${j+1}wan_port
//				set nat destination rule ${ipLast-10} source address 0.0.0.0/0
//				set nat destination rule ${ipLast-10} protocol tcp
//				set nat destination rule ${ipLast-10} translation address $target${j+1}_ip
//				set nat destination rule ${ipLast-10} translation port $target${j+1}_port
//				#将转发的端口开放
//				set firewall name $firename rule ${ipLast+80} action 'accept'
//				set firewall name $firename rule ${ipLast+80} protocol tcp
//				set firewall name $firename rule ${ipLast+80} destination port $target${j+1}wan_port
//	   	  	`
//	   	  	}
//	   	  	code += `
//	   	  	  commit
//            save`;
//          subnet.code  = code;
//          //console.log(code);
//	   	  }
          //下发基础配置
          this.loading = true;
		  this.minDown = 0;
//		  if(this.interval){
//			  clearInterval(this.interval);
//		  }
		    this.distriTip = '准备下发基础配置...';
		    let [error,returnData] = await this.awaitWrap(this.getSelHxRouterVms(this.adcBaseConfig,'攻防赛路由基础配置'));
   			if(error){
   				this.$Message.error('下发基础配置失败!');
   				this.loading = false;
   				return;
   			}
   			if(returnData.code == 1){
   				this.distriTip = '正在下发基础配置...';
   				let ids = returnData.data.map(item => item.id);
   				this.deBaseConfig(ids); //判断是否执行成功
   			}else{
   				this.$Message.error('下发基础配置失败!');
   				this.loading = false;
   			}
	    },
	    async deBaseConfig(ids){
	    	let [error,data] = await this.awaitWrap(this.getExecutionsResult(ids));
	    	if(error){
	    		//this.$Message.error('查询下发状态失败!');
   				this.loading = false;
   				return;
	    	}
	    	if(data.data.every(item => item.status == 2)){ //执行成功
	    		this.distriTip = '下发基础配置成功!';
	    		this.loading = false;
	    		this.$Message.info('下发基础配置成功!');
//				await this.awaitHiddenAll();
//				let [error3,returnData] = await this.awaitWrap(this.getSelHxRouterVmsAdc());
//				if(error3){
//					this.$Message.error('下发端口转发规则失败!');
//					this.loading = false;
//					return;
//				}
//				this.distriTip = '正在下发端口转发规则...';
//				let portForwardIds = returnData.data.map(item => item.id);
//				this.dePortForward(portForwardIds); //判断是否执行成功
		    }else if(data.data.some(item => item.status == 3)){
		    	//let data =
		    	this.$Message.error('下发基础配置失败!');
		    	this.distriTip = '下发基础配置失败!请检查原因，重新下发！';
		    	this.loading = false;
		    }else{
		    	this.timeout = setTimeout(() => {
		    		this.deBaseConfig(ids);
		    	},2000)
		    }
	    },
	    async awaitHiddenAll(){
	    	return new Promise(resolve =>{
	    		this.distriTip = '等待下发端口转发规则...';
	    		this.minDown = 60;
	    		this.interval = setInterval(() => {
					if(this.minDown > 0){
						this.minDown --;
					}else{
						clearInterval(this.interval);
						resolve();
					}
				},1000)
	    	})
	    },
	    async portForward(){
	    	if(this.hxRouterVmList.length == 0){
	    		this.$Message.info('没有核心路由，请查看工程是否部署，核心路由未下发！！！');
	    		return;
		    }
		   	for(let i = 0;i< this.subnetList.length;i++){
		   	  	let code = "#!/bin/vbash\nsource /opt/vyatta/etc/functions/script-template\n configure \n#指定变量 \nwancidr=192.168.50. \nwaneth=`ip a | grep  $wancidr | awk '{print $7}'`\nfirename=local\n";
		   	  	let subnet = this.subnetList[i];
		   	  	for(let j = 0;j<this.targetTeamData.length;j++){
		   	  		let target = this.targetTeamData[j];
		   	  		let ipLast = Number(target.ip.split('.').pop());
		   	  		code += `
	   	  		    target${j+1}_ip=${target.ip}
					target${j+1}_port=${target.servicePort}
					target${j+1}wan_ip=${subnet.ip}
					target${j+1}wan_port=${target.externalServicePort}
					#配置端口转发
					set nat destination rule ${ipLast-10} description 'Port Forward: $target${j+1}_ip:$target${j+1}_port to $target${j+1}wan_ip:$target${j+1}wan_port'
					set nat destination rule ${ipLast-10} inbound-interface $waneth
					set nat destination rule ${ipLast-10} destination address $target${j+1}wan_ip
					set nat destination rule ${ipLast-10} destination port $target${j+1}wan_port
					set nat destination rule ${ipLast-10} source address 0.0.0.0/0
					set nat destination rule ${ipLast-10} protocol tcp
					set nat destination rule ${ipLast-10} translation address $target${j+1}_ip
					set nat destination rule ${ipLast-10} translation port $target${j+1}_port
					#将转发的端口开放
					set firewall name $firename rule ${ipLast+80} action 'accept'
					set firewall name $firename rule ${ipLast+80} protocol tcp
					set firewall name $firename rule ${ipLast+80} destination port $target${j+1}wan_port
		   	  	`
		   	  	}
		   	  	code += `
		   	  	  commit
	              save`;
	            subnet.code  = code;
	            //console.log(code);
		   	}
	    	this.loading = true;
			let [error3,returnData] = await this.awaitWrap(this.getSelHxRouterVmsAdc());
			if(error3){
				this.$Message.error('下发端口转发规则失败!');
				this.loading = false;
				return;
			}
			this.distriTip = '正在下发端口转发规则...';
			let portForwardIds = returnData.data.map(item => item.id);
			this.dePortForward(portForwardIds); //判断是否执行成功
	    },
	    async dePortForward(ids){
	    	let [error,data] = await this.awaitWrap(this.getExecutionsResult(ids));
	    	if(error){
	    		//this.$Message.error('查询下发状态失败!');
   				this.loading = false;
   				return;
	    	}
	    	if(data.data.every(item => item.status == 2)){ //执行成功
	    		this.distriTip = '下发端口转发规则成功！！！';
	    		this.$Message.info('下发端口转发规则成功!');
	    		this.loading = false;
//	    		this.autoAllotTopoTarget();
		    }else if(data.data.some(item => item.status == 3)){
		    	//let data =
		    	this.$Message.error('下发端口转发规则失败!');
		    	this.distriTip = '下发端口转发规则失败!请检查原因，重新下发！';
		    	this.loading = false;
		    }else{
		    	this.timeout = setTimeout(() => {
		    		this.dePortForward(ids);
		    	},2000)
		    }
	    },
	    //下发核心路由
	    getSelHxRouterVmsAdc() {
	    	return new Promise((resolve,reject) => {
		    	let projectId = this.$route.query.prjid;
		    	let executionIns = this.hxRouterVmList.map(vm => {
		    		let code = this.subnetList.filter(subnet => subnet.id == vm.networkId)[0].code;
	          		//console.log(code,vm.networkName);
	          		let str = this.encode(code);
	          		return {
		          		content: str,
		                deviceId: vm.id,
		                enableDelete: false,
		                enableWrite: true,
		                ip: "192.168.100.1",
		                password: vm.access[0].password,
		                path: "/home/vyos/rule.sh",
		                port: vm.access[0].port,
		                type: vm.access[0].accessType,
		                username: vm.access[0].username,
		                description:'攻防赛端口转发规则'
		          	}
	            })
		    	hxRouterVms(projectId, executionIns).then(data => {
		            if (data.code == 1) {
		              //this.$Message.info('核心路由器下发成功');
		              resolve(data);
		            } else {
		              //this.$Message.error(data.message);
		              reject(data.message);
		            }
		        }).catch(error => {
		        	reject('下发失败!');
		        })
	    	})
       },
       getExecutionsResult(ids){
	    	return new Promise((resolve,reject) => {
		    	getExecutionsResult(ids).then(data => {
		    		if(data.code == 1){
		    			resolve(data);
		    		}else{
		    			this.$Message.error('查询下发状态失败!');
		    			reject('查询下发状态失败');
		    		}
		    	}).catch(error => {
		    		this.$Message.error('查询下发状态失败!');
		    		reject('查询下发状态失败');
		    	})
	    	})
	    },
	   autoAllotTopoTarget(){
	   	  autoAllotTopoTarget(this.$route.query.id).then(data => {
	   	  	if(data.code == 1){
	   	  		 this.$Message.info('操作成功');
                // 分配成功后清空搜索条件，回退到首页
                this.queryTargetAllotInfo.pageIndex = 1
                this.queryTargetAllotInfo.visibility = ''
                this.queryTargetAllotInfo.teamName = ''
                this.queryTargetAllotInfo.targetName = ''
	   	  		 this.queryTargetAllot();
	   	  	}else{
	   	  		this.$Message.error({
	   	  			content:data.message,
	   	  			duration:2
	   	  		});
	   	  	}
	   	  }).catch(error => {
	   	  	this.$Message.error(data.message);
	   	  })
	   },
	   VRIPRelation(){
		   	let params = this.formValidate.idsTOS.map(item => {
		   		return {
				    "contestId": this.$route.query.id,
				    "ip": this.idwithName[this.formValidate.targetId].ip,
				    "targetName":this.idwithName[this.formValidate.targetId].name,
				    "teamId": item.teamId,
				    "teamName": item.teamName,
				    "virtualRouterIP": item.externalIp,
				    "vmname": item.vmName
				}
		   	})
	   	    VRIPRelation(params).then(data => {
	   	   		if(data.code == 1){

	   	    	}
	   	   })
	   },
	   //queryTargetAllot,queryTargetAllotRelation,modifyTargetAllot
	   queryTargetAllot(){
			this.selectAll = false
	   		queryTargetAllot(this.queryTargetAllotInfo).then(data => {
	   			if(data.code == 1){
	   				this.targetAllotList = data.data.items;
	   				this.targetAllotTotal = data.data.total;
	   				if(this.step == 'pre'){
		   				if(this.targetAllotTotal > 0){
		   					this.$emit('setHasTarget',true);
		   				}else{
		   					this.$emit('setHasTarget',false);
		   				}
		   			}
	   			}else{
	   				this.$Message.warning(data.message);
	   				if(this.step == 'pre'){
	   					this.$emit('setHasTarget',false);
	   				}
	   			}
	   		}).catch(error => {
	   			this.$Message.error(error);
	   			if(this.step == 'pre'){
	   				this.$emit('setHasTarget',false);
	   			}
	   		})
	   },
	   queryTargetAllotRelation(){
	   	   let params = {
	   	   	   pageIndex:1,
	   	   	   pageSize:1000,
//	   	   	   subnetId:this.formValidate.subnetId,
	   	   	   basicTargetId:this.formValidate.targetId,
	   	   	   sceneId:this.$route.query.id
	   	   }
	   		queryTargetAllotRelation(params).then(data => {
	   			if(data.code == 1){
	   				this.formValidate.idsTOS = data.data.items;
//	   				if(data.data.items.length > 0){
//	   					this.formValidate.subnetId = data.data.items[0].subnetId;
//	   					this.formValidate.subnetName = data.data.items[0].subnetName;
//	   					this.getAllVmlist();
//	   				}
	   			}else{
	   			this.$Message.warning(data.message);
	   		  }
	   	    }).catch(error => {
	   			this.$Message.error(error);
	   		})
	       },
	  	   modifyTargetAllot(){
	   	    this.$refs['allotFormValidate'].validate((valid) => {
	            if (valid) {
			   	   let params = {
			   	   	  "createTime":this.allotFormValidate.createTime,
					  "externalIp": this.allotFormValidate.externalIp,
//					  "externalPort": this.allotFormValidate.externalPort,
//					  "externalServicePort":this.allotFormValidate.externalServicePort,
					  "id": this.allotFormValidate.id,
					  "sceneId": this.allotFormValidate.sceneId,
					  "subnetId": this.allotFormValidate.subnetId,
					  "subnetName": this.idwithName[this.allotFormValidate.subnetId].name,
					  "basicTargetId": this.allotFormValidate.basicTargetId,
					  "targetName": this.idwithName[this.allotFormValidate.basicTargetId].name,
					  "teamId": this.allotFormValidate.teamId,
					  "teamName": this.idwithName[this.allotFormValidate.teamId].name,
					  "visibility": this.allotFormValidate.visibility,
					  "vmId": this.allotFormValidate.vmId,
					  "vmName": this.idwithName[this.allotFormValidate.vmId].name,
			   	   }
			   	   modifyTargetAllot(params.id,params).then(data => {
			   	   	  if(data.code == 1){
			   	   	  	this.queryTargetAllot();
			   	   	  	this.modifyTargetModal.show = false;
			   	   	  	this.cancelLoading('modifyTargetModal');
			   	   	  	this.$Message.info('操作成功');
			   	   	  }else{
			   			this.$Message.warning(data.message);
			   		  }
			   	    }).catch(error => {
			   			this.$Message.error(error);
			   			this.cancelLoading('modifyTargetModal');
			   		})
			   	}else{
			   		this.cancelLoading('modifyTargetModal');
			   	}
	        })
	   },
	   cancelLoading(name){
	    	this[name].loading = false;
	      	setTimeout(() => {
	      		this[name].loading = true;
	      	})
	    },
	    closeTargetModal(){
	    	this.handleReset('formValidate');
	    	this.handleReset('addFormValidate');
	    },
      showModifyPwd(){
    	  this.$refs.modifyPwd.showModel(this.routeParams.id,this.accessGroupList);
      }
    }
}
</script>

<style>
  .drillsTable .ivu-poptip-body {
    text-align: left!important;
  }
  .scenesHeader{
    margin-bottom: 16px;
  }
  .drillTables{
    min-height: 300px;
  }
  .drillsTable.ivu-table-wrapper{
    overflow: inherit;
  }
    .demo-spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }
    @keyframes ani-demo-spin {
        from { transform: rotate(0deg);}
        50%  { transform: rotate(180deg);}
        to   { transform: rotate(360deg);}
    }
</style>
<style scoped>
    .card-list-div>>>#cardList {
        width: 100%;
    }
  .targetHeader{
    /*padding: 10px;*/
    margin: 15px 0;
  }
  .mr15 {
	  margin-right: 15px;
  }
</style>
